package com.haiyou.dc.message.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.haiyou.dc.message.constant.OpenfireConstant;
import com.haiyou.dc.message.entity.ImMessage;
import com.haiyou.dc.message.service.PacketService;
import com.haiyou.dc.message.util.HttpUtil;
import com.haiyou.dc.message.util.RedisUtils;
import com.haiyou.dc.message.util.SendMsgUtil;
import com.haiyou.dc.message.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.jivesoftware.openfire.OfflineMessage;
import org.jivesoftware.openfire.OfflineMessageStore;
import org.jivesoftware.openfire.session.Session;
import org.xmpp.packet.JID;
import org.xmpp.packet.Message;
import org.xmpp.packet.Packet;

import java.util.Collection;
import java.util.Date;

/**
 * openfire消息包体逻辑处理
 * @author pc
 */
@Slf4j
public class MessageServiceImpl implements PacketService {

    @Override
    public void handler(Packet packet, Session session) {
        Message message = (Message) packet;
        String body = message.getBody();

        log.info("openfire消息体body====>" + body);
        if (StringUtil.isBlank(body)) {
            log.warn("================>body is empty================>" + packet.toString());
            return;
        }

        try {
            JSONObject json = JSON.parseObject(body);

            String msgId = json.getString("msgId");
            Date date = new Date();
            // 设置发送时间
            json.put("time", date.getTime());
            json.put("id", msgId);
            message.setBody(json.toJSONString());
            // 1单聊，2群聊
            String type = json.getString(OpenfireConstant.TYPE);
            ImMessage imMessage = new ImMessage();
            imMessage.setBody(json.toJSONString());
            imMessage.setSource("0");
            imMessage.setCreateTime(date);
            imMessage.setId(msgId);
            imMessage.setType(type);
            if (StringUtil.isBlank(type) || OpenfireConstant.SINGLE_CHAT.equals(type)) {
                imMessage.setReceiver(json.getString("receiver"));
                imMessage.setU1U2(StringUtil.compare(json.getString("sender"), json.getString("receiver")));
                //保存单聊会话
                RedisUtils.saveSingleSession(json.getString("sender"), json.getString("receiver"));
                String result = HttpUtil.doPostByRaw(OpenfireConstant.SAVE_MSG_URL, JSON.toJSONString(imMessage));
                log.info("单聊===>" + json + ",result===>" + result);
            } else if (OpenfireConstant.GROUP_CHAT.equals(type)) {
                imMessage.setGroupName(json.getString("groupName"));
                //保存群会话
                RedisUtils.saveGroupSession(json.getString("sender"), json.getString("groupName"));
                String result = HttpUtil.doPostByRaw(OpenfireConstant.SAVE_MSG_URL, JSON.toJSONString(imMessage));
                log.info("群聊===>" + json + ",result===>" + result);
            } else if (OpenfireConstant.WITHDRAW.equals(type)) {
                //删除openfire离线
                JID to = message.getTo();
                String receiver = to.getNode();
                Collection<OfflineMessage> messages = OfflineMessageStore.getInstance().getMessages(receiver, false);
                for (OfflineMessage offlineMessage : messages) {
                    if (offlineMessage.getTo().getNode().equals(receiver) && offlineMessage.toString().contains(msgId)) {
                        OfflineMessageStore.getInstance().deleteMessage(to.getNode(), offlineMessage.getCreationDate());
                        break;
                    }
                }
                //发送消息给接收者删除
                String withdrawInfo = String.format("{\"receiver\":\"%s\",\"type\":\"withdraw\",\"msgId\":\"%s\"}", receiver, msgId);
                SendMsgUtil.sendMsg(withdrawInfo);

                //删除数据库消息
                imMessage.setId(msgId);
                String result = HttpUtil.doPostByRaw(OpenfireConstant.DELETE_WITHDRAW_MSG_URL, JSON.toJSONString(imMessage));
                log.info("撤回===>" + json + ",result===>" + result);
            }
        } catch (JSONException e) {
            log.error("body非json结构体异常,body===>" + body, e);
        } catch (Exception e) {
            log.error("其他异常,body==>" + body, e);
        }
    }
}
